import { ChatManager } from '../core/chat';
import { modelManager } from '../core/models';
import { configManager } from '../utils/config';

export interface Command {
  name: string;
  description: string;
  execute: (args: string[], chatManager: ChatManager, cli?: any) => Promise<void> | void;
}

export class CommandManager {
  private commands: Map<string, Command> = new Map();

  constructor() {
    this.registerDefaultCommands();
  }

  private registerDefaultCommands() {
    this.registerCommand({
      name: "config",
      description: "显示当前配置",
      execute: (args) => {
        const action = args[0];
        
        if (action === 'show' || !action) {
          console.log('\n=== 当前配置 ===');
          console.log(`🌡️  Temperature: ${configManager.get('temperature')}`);
          console.log(`📊 Max Tokens: ${configManager.get('maxTokens')}`);
          console.log(`🔄 Enable Tools: ${configManager.get('enableTools')}`);
          console.log(`📶 Stream Output: ${configManager.get('streamOutput')}`);
          console.log(`🧠 Show Thinking: ${configManager.get('showThinking')}`);
          console.log(`💾 Auto Save: ${configManager.get('autoSave')}`);
          console.log('================\n');
        } else if (action === 'temp' && args[1]) {
          const newTemp = parseFloat(args[1]);
          if (!isNaN(newTemp) && newTemp >= 0 && newTemp <= 2) {
            configManager.set('temperature', newTemp);
            console.log(`\n✅ Temperature 已设置为: ${newTemp}`);
          } else {
            console.log('\n❌ Temperature 必须在 0-2 之间');
          }
        } else if (action === 'tokens' && args[1]) {
          const newTokens = parseInt(args[1]);
          if (!isNaN(newTokens) && newTokens > 0 && newTokens <= 8000) {
            configManager.set('maxTokens', newTokens);
            console.log(`\n✅ Max Tokens 已设置为: ${newTokens}`);
          } else {
            console.log('\n❌ Max Tokens 必须在 1-8000 之间');
          }
        } else {
          console.log('\n用法: /config [show|temp <数字>|tokens <数字>]');
          console.log('  show         - 显示当前配置');
          console.log('  temp 0.7     - 设置 temperature (0-2)');
          console.log('  tokens 4000  - 设置 max_tokens (1-8000)');
        }
      }
    });

    this.registerCommand({
      name: "debug",
      description: "切换调试模式",
      execute: (args, chatManager, cli) => {
        if (cli && typeof cli.toggleDebugMode === 'function') {
          cli.toggleDebugMode();
        } else {
          console.log('\n❌ 调试模式不可用');
        }
      }
      });

      this.registerCommand({
        name: "history",
        description: "历史记录管理 (list|save|toggle)",
        execute: (args, chatManager, cli) => {
          const action = args[0] || 'list';
          
          if (action === 'list') {
            if (cli && typeof cli.showHistoryList === 'function') {
              cli.showHistoryList();
            } else {
              console.log('\n❌ 历史记录功能不可用');
            }
          } else if (action === 'save') {
            console.log('\n💾 历史记录已自动保存，无需手动保存');
          } else if (action === 'toggle') {
            if (cli && typeof cli.toggleHistorySaving === 'function') {
              const enabled = cli.toggleHistorySaving();
              console.log(`\n💾 历史记录保存: ${enabled ? '已启用' : '已禁用'}`);
            } else {
              console.log('\n❌ 历史记录功能不可用');
            }
          } else {
            console.log('\n❌ 未知的历史操作，使用: list, save, toggle');
          }
        }
      });

      this.registerCommand({
        name: "exit",
        description: "退出对话",
        execute: () => {
          console.log('\n=== 对话结束 ===');
          process.exit(0);
        }
      });

      this.registerCommand({
        name: "help",
        description: "显示帮助信息",
        execute: () => {
          this.showHelp();
        }
      });
    }

  registerCommand(command: Command) {
    this.commands.set(command.name, command);
  }

  async executeCommand(input: string, chatManager: ChatManager, cli?: any): Promise<boolean> {
    if (!input.startsWith('/')) {
      return false;
    }

    const parts = input.slice(1).split(' ');
    const commandName = parts[0].toLowerCase();
    const args = parts.slice(1);

    const command = this.commands.get(commandName);
    if (!command) {
      console.log(`\n❌ 未知命令: ${commandName}`);
      console.log('输入 /help 查看可用命令');
      return true;
    }

    try {
      await command.execute(args, chatManager, cli);
    } catch (error) {
      console.log(`\n❌ 执行命令失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }

    return true;
  }

    showHelp() {
      console.log('\n=== 可用命令 ===');
      
      this.commands.forEach((command, name) => {
        console.log(`/${name} - ${command.description}`);
      });
      
      console.log('\n=== 使用说明 ===');
      console.log('• 直接输入问题与AI对话');
      console.log('• 使用 / 开头输入命令');
      console.log('• AI会根据需要自动调用工具');
      console.log('• 🐛 使用 /debug 切换调试模式查看详细信息');
      console.log('• ⚙️  使用 /config 查看和修改配置');
      console.log('• 💾 使用 /history 管理历史记录');
      console.log('• 📚 历史记录自动保存到 chat_history/ 目录');
      console.log('================\n');
    }

  getCommands(): Command[] {
    return Array.from(this.commands.values());
  }
}
